const router = require('koa-router')()
const userService = require('../controller/mysqlConfig');
const getNowFormatDate = require('../controller/getDateTime');
const svgCaptcha = require('../controller/svgCaptcha')
let fs = require('fs')
const jwt = require('jsonwebtoken');
const util = require('util');
const verify = util.promisify(jwt.verify);

router.prefix('/app')   //在路径前加前缀

let textsvg = ""       //定义验证码全局变量
//----------------------------------个人中心数据
    let orderid = ""   //订单id
    let order_no = ""  //订单号
    let user_id = ""   //用户id
    let shipping_id = "" //地址id
    let payment = ""   //订单金额
    let status = ""    //订单状态
    let orderArr = []
//----------------------------------个人中心数据


//登录页获取验证码接口
router.get('/home',async(ctx,next)=>{
  await svgCaptcha.getString().then(async(res)=>{
      ctx.session.userid = true
      textsvg = res.textpsd
      ctx.body={
        code:"800000", 
        data:res,
        mess:"上传成功"
      }
  })
})

//登录页
router.post('/login',async(ctx,next)=>{
    let ctxsvg = ctx.request.body.svgcode
    let username = ctx.request.body.username
    let password = ctx.request.body.passward
    if(ctxsvg!=textsvg){
      ctx.body={
        code:"800003",
        data:"",
        mess:"验证码错误"
      }
    }else{
      //去数据库查询用户名和密码
      await userService.userlogin(username,password).then((res)=>{
            if(res.length){  
              const token = jwt.sign(
                {name: res[0].name,_id: res[0].id}, 
                'secret', 
                { expiresIn: '1min' }
              );
            ctx.body={
              code:"800000",
              data:token+"^"+res[0].id,
              mess:"登录成功"
            }
          }
      })
    }
    await next(); 
})

///鉴权先停下，后期处理
router.get('/app',async(ctx,next)=>{
  await userService.getcategory().then((res)=>{
     if(res.length){
      ctx.body={
        code:"800000",
        data:res,
        mess:"success"
      }
     }
  })
  // try {
  //     let payload = getJWTPayload(ctx.headers.authorization)
  // } catch (error) {
  //     console.log(error+"=========")
  // }
})

///获取商品信息
router.post('/getgoodlist',async(ctx,next)=>{
  let id = ctx.request.body.id
  await userService.getgoodlist(id).then((res)=>{
     if(res.length){
       ctx.body={
          code:"800000",
          data:res,
          mess:"success"
       }
     }else{
      ctx.body={
        code:"800004",
        data:"",
        mess:"error"
     }
     }
  })
})

///获取商品详情信息信息
router.post('/getgoodinfo',async(ctx,next)=>{
  let id = ctx.request.body.id
  await userService.getgoodinfo(id).then((res)=>{
     if(res.length){
        ctx.body={
          code:"800000",
          data:res,
          mess:"success"
        }
     }else{
      ctx.body={
        code:"800004",
        data:"",
        mess:"error"
     }
     }
  })
})


///个人中心页面初始化一些数据
router.post('/personaldata',async(ctx,next)=>{
  let userid = ctx.request.body.userid
  let status = ctx.request.body.status
  await userService.getpersonaldata(userid,status).then(async(resed)=>{
     if(resed.length){
        for(key in resed){
            let order_noo = resed[key].order_no;
            let user_ido = resed[key].user_id;
            await userService.orderitem(order_noo,user_ido).then((res)=>{
              if(res.length){
                resed[key]['product_name']= res[0].product_name;
                resed[key]['product_image']= res[0].product_image;
                resed[key]['price']= res[0].total_price;
              }
            })
        }
        ctx.body={
          code:"800000",
          data:resed,
          mess:"success"
        }
     }else{
      ctx.body={
        code:"800004",
        data:"",
        mess:"error"
     }
     }
  })
})


///获取所有分类详情
router.get('/getcateall',async(ctx,next)=>{
  await userService.getcategoryed().then((res)=>{
     if(res.length){
        ctx.body={
          code:"800000",
          data:res,
          mess:"success"
        }
     }else{
      ctx.body={
        code:"800004",
        data:"",
        mess:"error"
     }
     }
  })
})


///获取所有子分类
router.post('/getcateinfos',async(ctx,next)=>{
  let id = ctx.request.body.id
  await userService.getsoncate(id).then((res)=>{
     if(res.length){
        ctx.body={
          code:"800000",
          data:res,
          mess:"success"
        }
     }else{
      ctx.body={
        code:"800004",
        data:"",
        mess:"error"
     }
     }
  })
})

/* 通过token获取JWT的payload部分 */
function getJWTPayload(token) {
  // 验证并解析JWT
  return verify(token.split(' ')[1], 'secret');
}
module.exports = router
